<template>
  <div class="azm-rich-text-editor" :contenteditable="true" @input="__handleInput"
       @blur="__handleBlur" @change="__handleChange" @focus="__handleFocus">
    <div v-for="(item,index) in textArr" :key="index">{{item}}</div>
  </div>
</template>

<script>
  import { mapState } from 'vuex'

  export default {
    name: 'rich-text-editor',
    components: {},
    props: {
      value: String
    },
    watch: {},
    data () {
      let value = this.value.split(/\r?\n|\n/g)
      return {
        message: '',
        inputValue: this.value,
        editShow: false,
        textArr: value
      }
    },
    computed: {
      ...mapState({})
    },
    inject: [],
    created () {
      this.$nextTick(function () {

      })
    },
    methods: {
      __handleInput (e) {
        let that = this
        let $ = that.util.Zepto
        let dom = $(that.$el)
        let str = dom.html()
        if (/^<(div|p)[^>]*>(<br\\?>)[\s\S]+<\/[^>]*(div|p)>/gi.test(str) && /^<(div|p)[^>]*>(<br\\?>)?/gi.test(str)) {
          str = str.replace(/^<(div|p)[^>]*>/gi, '\r\n')
        } else {
          str = str.replace(/^<(div|p)[^>]*>/gi, '')
        }
        // str = str.replace(/^<(div|p)[^>]*><\/[a-z]+>/gi, '');
        // str = str.replace(/^<(div|p)[^>]*>(<br\\?>)/gi, '\r\n');
        str = str.replace(/<(span)[^>]*>(<br\\?>)?/gi, '')
        str = str.replace(/<(div|p)[^>]*>(<br\\?>)?/gi, '\r\n')
        str = str.replace(/<\/[a-z]+>/gi, '')
        str = str.replace(/&nbsp;/gi, ' ')
        str = str.replace(/<br\\?>/, '\r\n')
        that.$emit('input', str)
        setTimeout(function () {
          that.__handleChange(str)
        }, 100)
      },
      __handleChange (val) {
        console.log(val)
      },
      __handleBlur (e) {
        this.$emit('blur', e)
      },
      __handleFocus (e) {
        this.$emit('focus', e)
      }
    }
  }
</script>

<style scoped lang="less">
  .azm-rich-text-editor {

  }
</style>
<style lang="less">
  .azm-rich-text-editor {
    user-select: text;
    font-family: inherit;
    line-height: 1.2;
    font-size: 12px;
    text-align: left;
    min-width: 50px;
    min-height: 10px;
    padding: 0;
    display: inline-block;

    * {
      font-family: inherit;
      line-height: inherit;
      font-size: inherit;
      text-align: inherit;
    }
  }
</style>
